<template>
  <div class="communication-bus">
    <div class="page-header">
      <h1 class="title">通信总线场景库</h1>
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon><Plus /></el-icon> 添加总线场景
      </el-button>
    </div>

    <!-- 搜索与筛选 -->
    <search-form v-model="searchForm" :loading="loading" @search="handleSearch" @reset="handleReset">
      <el-form-item label="总线名称">
        <el-input v-model="searchForm.name" placeholder="请输入总线名称" clearable />
      </el-form-item>
      <el-form-item label="总线类型">
        <el-select v-model="searchForm.type" placeholder="请选择总线类型" clearable>
          <el-option label="工业控制总线" value="industrial" />
          <el-option label="航空总线" value="aviation" />
          <el-option label="通用接口总线" value="general" />
        </el-select>
      </el-form-item>
    </search-form>

    <!-- 总线类型选项卡 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部总线" name="all"></el-tab-pane>
      <el-tab-pane label="工业控制总线" name="industrial"></el-tab-pane>
      <el-tab-pane label="航空总线" name="aviation"></el-tab-pane>
      <el-tab-pane label="通用接口总线" name="general"></el-tab-pane>
    </el-tabs>

    <!-- 总线卡片列表 -->
    <div class="bus-list">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(bus, index) in filteredBuses" :key="index">
          <el-card shadow="hover" class="bus-card" @click="showBusDetail(bus)">
            <div class="bus-image">
              <el-image :src="bus.image" fit="cover"></el-image>
              <div class="bus-badge">{{ getBusTypeLabel(bus.type) }}</div>
            </div>
            <div class="bus-info">
              <h3 class="bus-name">{{ bus.name }}</h3>
              <p class="bus-desc">{{ bus.description }}</p>
              <div class="bus-meta">
                <span class="bus-speed">速率: {{ bus.speed }}</span>
                <span class="bus-interface">接口: {{ bus.interface }}</span>
              </div>
              <div class="bus-footer">
                <el-button type="primary" size="small" @click.stop="showBusDetail(bus)">查看详情</el-button>
                <el-button type="success" size="small" @click.stop="createPlanWithBus(bus)">创建方案</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 总线详情对话框 -->
    <el-dialog
      :title="currentBus.name"
      v-model="detailDialogVisible"
      width="70%"
      top="5vh"
    >
      <div class="bus-detail" v-if="currentBus.id">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总线类型">{{ getBusTypeLabel(currentBus.type) }}</el-descriptions-item>
          <el-descriptions-item label="传输速率">{{ currentBus.speed }}</el-descriptions-item>
          <el-descriptions-item label="物理接口">{{ currentBus.interface }}</el-descriptions-item>
          <el-descriptions-item label="应用场景">{{ currentBus.application }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>总线描述</h4>
          <p>{{ currentBus.description }}</p>
        </div>
        
        <div class="detail-section">
          <h4>总线架构</h4>
          <div class="architecture-image">
            <el-image 
              :src="currentBus.architectureImage" 
              fit="contain"
              :preview-src-list="[currentBus.architectureImage]"
            ></el-image>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>通信协议</h4>
          <div class="protocol-info">
            <p>{{ currentBus.protocol }}</p>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>安全特性</h4>
          <div class="security-info">
            <p>{{ currentBus.security }}</p>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>潜在漏洞</h4>
          <el-tag 
            v-for="(vulnerability, index) in currentBus.vulnerabilities" 
            :key="index"
            type="danger"
            effect="dark"
            class="vulnerability-tag"
          >
            {{ vulnerability }}
          </el-tag>
        </div>
      </div>
    </el-dialog>

    <!-- 添加总线对话框 -->
    <el-dialog
      title="添加总线场景"
      v-model="dialogVisible"
      width="60%"
    >
      <el-form 
        ref="busFormRef"
        :model="busForm"
        label-width="100px"
        :rules="busRules"
      >
        <el-form-item label="总线名称" prop="name">
          <el-input v-model="busForm.name" placeholder="请输入总线名称"></el-input>
        </el-form-item>
        <el-form-item label="总线类型" prop="type">
          <el-select v-model="busForm.type" placeholder="请选择总线类型" style="width: 100%">
            <el-option label="工业控制总线" value="industrial"></el-option>
            <el-option label="航空总线" value="aviation"></el-option>
            <el-option label="通用接口总线" value="general"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="传输速率" prop="speed">
          <el-input v-model="busForm.speed" placeholder="请输入传输速率"></el-input>
        </el-form-item>
        <el-form-item label="物理接口" prop="interface">
          <el-input v-model="busForm.interface" placeholder="请输入物理接口"></el-input>
        </el-form-item>
        <el-form-item label="应用场景" prop="application">
          <el-input v-model="busForm.application" placeholder="请输入应用场景"></el-input>
        </el-form-item>
        <el-form-item label="总线描述" prop="description">
          <el-input type="textarea" v-model="busForm.description" rows="3" placeholder="请输入总线描述"></el-input>
        </el-form-item>
        <el-form-item label="通信协议" prop="protocol">
          <el-input type="textarea" v-model="busForm.protocol" rows="3" placeholder="请描述通信协议"></el-input>
        </el-form-item>
        <el-form-item label="安全特性" prop="security">
          <el-input type="textarea" v-model="busForm.security" rows="3" placeholder="请描述安全特性"></el-input>
        </el-form-item>
        <el-form-item label="潜在漏洞">
          <el-tag
            v-for="(tag, index) in busForm.vulnerabilities"
            :key="index"
            closable
            type="danger"
            @close="handleVulnerabilityClose(tag)"
            class="vulnerability-input-tag"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="vulnerabilityInputVisible"
            ref="vulnerabilityInputRef"
            v-model="vulnerabilityInputValue"
            class="vulnerability-input"
            size="small"
            @keyup.enter="handleVulnerabilityInputConfirm"
            @blur="handleVulnerabilityInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showVulnerabilityInput">
            + 添加漏洞
          </el-button>
        </el-form-item>
        <el-form-item label="总线图片">
          <el-upload
            class="upload-container"
            action="#"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="架构图片">
          <el-upload
            class="upload-container"
            action="#"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import SearchForm from '@/components/SearchForm/index.vue';

/**
 * 搜索表单数据
 * @type {Object}
 */
const searchForm = reactive({
  name: '',
  type: ''
});

/**
 * 当前选中的选项卡
 * @type {Ref<string>}
 */
const activeTab = ref('all');

/**
 * 详情弹窗可见性
 * @type {Ref<boolean>}
 */
const detailDialogVisible = ref(false);

/**
 * 添加总线弹窗可见性
 * @type {Ref<boolean>}
 */
const dialogVisible = ref(false);

/**
 * 当前选中的总线
 * @type {Ref<Object>}
 */
const currentBus = ref({});

/**
 * 总线表单引用
 * @type {Ref<Object|null>}
 */
const busFormRef = ref(null);

/**
 * 添加漏洞输入可见性
 * @type {Ref<boolean>}
 */
const vulnerabilityInputVisible = ref(false);

/**
 * 添加漏洞输入值
 * @type {Ref<string>}
 */
const vulnerabilityInputValue = ref('');

/**
 * 添加漏洞输入引用
 * @type {Ref<Object|null>}
 */
const vulnerabilityInputRef = ref(null);

/**
 * 总线表单数据
 * @type {Object}
 */
const busForm = reactive({
  name: '',
  type: '',
  speed: '',
  interface: '',
  application: '',
  description: '',
  protocol: '',
  security: '',
  vulnerabilities: [],
  image: '',
  architectureImage: ''
});

/**
 * 总线表单验证规则
 * @type {Object}
 */
const busRules = {
  name: [
    { required: true, message: '请输入总线名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择总线类型', trigger: 'change' }
  ],
  speed: [
    { required: true, message: '请输入传输速率', trigger: 'blur' }
  ],
  interface: [
    { required: true, message: '请输入物理接口', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入总线描述', trigger: 'blur' }
  ]
};

/**
 * 总线数据列表
 * @type {Ref<Array>}
 */
const busList = ref([
  {
    id: 1,
    name: 'CAN总线',
    type: 'industrial',
    description: 'Controller Area Network，一种用于车辆和工业控制系统的串行通信总线，支持分布式实时控制。',
    speed: '最高1Mbps',
    interface: 'DB9接口',
    application: '汽车电子控制单元、工业控制系统',
    protocol: 'CAN协议采用基于CSMA/CD+AMP的总线仲裁机制，使用短帧结构和高效的错误检测机制。',
    security: 'CAN总线本身没有内置的加密和认证机制，易受到被动监听和主动注入攻击。',
    vulnerabilities: ['消息伪造', '消息重放', '总线拒绝服务'],
    image: 'https://via.placeholder.com/400x250?text=CAN-Bus',
    architectureImage: 'https://via.placeholder.com/800x500?text=CAN-Architecture'
  },
  {
    id: 2,
    name: 'RS485总线',
    type: 'industrial',
    description: '一种平衡传输的串行通信总线标准，适用于远距离、噪声环境下的数据传输。',
    speed: '最高10Mbps',
    interface: 'DB9/螺丝端子',
    application: '工业自动化、楼宇控制、安防系统',
    protocol: 'RS485定义了物理层规范，通常与Modbus等协议配合使用，支持多点通信和较长距离传输。',
    security: 'RS485没有内置安全机制，需要在上层协议中实现加密和认证功能。',
    vulnerabilities: ['数据窃听', '协议漏洞', '终端设备破解'],
    image: 'https://via.placeholder.com/400x250?text=RS485-Bus',
    architectureImage: 'https://via.placeholder.com/800x500?text=RS485-Architecture'
  },
  {
    id: 3,
    name: 'Modbus总线',
    type: 'industrial',
    description: '一种应用层通信协议，广泛应用于工业自动化系统，支持主从通信模式。',
    speed: '取决于物理层',
    interface: 'RS485/以太网',
    application: '工业控制、能源管理、自动化系统',
    protocol: 'Modbus是一种请求/响应协议，定义了消息格式和通信规则，支持RTU和TCP等多种传输模式。',
    security: 'Modbus协议没有内置安全机制，通信内容明文传输，易受攻击。',
    vulnerabilities: ['功能码扫描', '非法操作码', '数据篡改'],
    image: 'https://via.placeholder.com/400x250?text=Modbus',
    architectureImage: 'https://via.placeholder.com/800x500?text=Modbus-Architecture'
  },
  {
    id: 4,
    name: '1553B总线',
    type: 'aviation',
    description: 'MIL-STD-1553B是一种军用标准总线，用于航空航天领域的数据传输和控制。',
    speed: '1Mbps',
    interface: '三轴隔离耦合器',
    application: '军用飞机、卫星、武器系统',
    protocol: '1553B采用时分多路访问控制方式，支持主控制器、远程终端和总线监视器三种设备类型。',
    security: '具有较高的电磁兼容性和冗余设计，但缺乏现代加密机制。',
    vulnerabilities: ['协议分析', '总线控制劫持', '终端仿冒'],
    image: 'https://via.placeholder.com/400x250?text=1553B-Bus',
    architectureImage: 'https://via.placeholder.com/800x500?text=1553B-Architecture'
  },
  {
    id: 5,
    name: 'ARINC429总线',
    type: 'aviation',
    description: '一种用于民用航空电子设备之间数据传输的单向串行数据总线标准。',
    speed: '12.5kbps或100kbps',
    interface: '三线接口',
    application: '民用航空电子系统、飞行控制系统',
    protocol: 'ARINC429使用单向通信模式，每条总线只有一个发送器和多个接收器，数据以32位字传输。',
    security: '物理隔离提供了一定安全性，但缺乏加密与认证机制。',
    vulnerabilities: ['数据监听', '参数篡改', '信号干扰'],
    image: 'https://via.placeholder.com/400x250?text=ARINC429',
    architectureImage: 'https://via.placeholder.com/800x500?text=ARINC429-Architecture'
  },
  {
    id: 6,
    name: 'USB接口',
    type: 'general',
    description: 'Universal Serial Bus，通用串行总线，是一种广泛用于计算机外设连接的接口标准。',
    speed: '最高40Gbps (USB4)',
    interface: 'Type-A/B/C',
    application: '计算机外设、消费电子、工业设备',
    protocol: 'USB协议包括物理层、事务层和协议层，采用主从架构，支持即插即用和热插拔。',
    security: '新版USB支持数据加密，但存在多种物理和协议层安全隐患。',
    vulnerabilities: ['恶意固件', 'BadUSB攻击', '数据窃取'],
    image: 'https://via.placeholder.com/400x250?text=USB',
    architectureImage: 'https://via.placeholder.com/800x500?text=USB-Architecture'
  },
  {
    id: 7,
    name: 'RS232接口',
    type: 'general',
    description: '一种常见的串行通信接口标准，用于计算机和外设之间的通信。',
    speed: '最高115.2kbps',
    interface: 'DB9/DB25',
    application: '工业控制设备、传统串口设备、嵌入式系统',
    protocol: 'RS232定义了点对点通信的物理层标准，使用不平衡传输方式，数据按位串行传输。',
    security: '没有内置的安全机制，通信内容明文传输。',
    vulnerabilities: ['数据窃听', '命令注入', '协议漏洞'],
    image: 'https://via.placeholder.com/400x250?text=RS232',
    architectureImage: 'https://via.placeholder.com/800x500?text=RS232-Architecture'
  }
]);

/**
 * 根据筛选条件过滤总线列表
 */
const filteredBuses = computed(() => {
  let result = busList.value;
  
  // 按选项卡类型过滤
  if (activeTab.value !== 'all') {
    result = result.filter(bus => bus.type === activeTab.value);
  }
  
  // 按名称搜索
  if (searchForm.name) {
    result = result.filter(bus => bus.name.includes(searchForm.name));
  }
  
  // 按类型搜索
  if (searchForm.type) {
    result = result.filter(bus => bus.type === searchForm.type);
  }
  
  return result;
});

/**
 * 获取总线类型标签
 * @param {string} type - 总线类型
 * @returns {string} 总线类型标签
 */
function getBusTypeLabel(type) {
  const typeMap = {
    'industrial': '工业控制总线',
    'aviation': '航空总线',
    'general': '通用接口总线'
  };
  return typeMap[type] || type;
}

/**
 * 显示总线详情
 * @param {Object} bus - 总线对象
 */
function showBusDetail(bus) {
  currentBus.value = bus;
  detailDialogVisible.value = true;
}

/**
 * 使用总线创建方案
 * @param {Object} bus - 总线对象
 */
function createPlanWithBus(bus) {
  // 在实际应用中跳转到方案创建页面，并传入总线信息
  console.log('使用总线创建方案:', bus.name);
  // router.push({
  //   path: '/tactical-plan/create',
  //   query: { busId: bus.id }
  // });
  
  // 临时提示
  ElMessage({
    message: `即将使用 ${bus.name} 创建新方案`,
    type: 'success'
  });
}

/**
 * 页面加载状态
 * @type {Ref<boolean>}
 */
const loading = ref(false);

/**
 * 处理搜索操作
 */
const handleSearch = () => {
  // 这里可以添加API调用逻辑
  console.log('搜索条件:', searchForm);
}

/**
 * 重置搜索条件
 */
const handleReset = () => {
  // 重置操作已由SearchForm组件内部处理
  handleSearch();
}

/**
 * 处理选项卡点击
 */
function handleTabClick() {
  console.log('当前选项卡:', activeTab.value);
}

/**
 * 显示添加漏洞输入框
 */
function showVulnerabilityInput() {
  vulnerabilityInputVisible.value = true;
  nextTick(() => {
    vulnerabilityInputRef.value?.focus();
  });
}

/**
 * 处理漏洞输入确认
 */
function handleVulnerabilityInputConfirm() {
  if (vulnerabilityInputValue.value) {
    busForm.vulnerabilities.push(vulnerabilityInputValue.value);
  }
  vulnerabilityInputVisible.value = false;
  vulnerabilityInputValue.value = '';
}

/**
 * 处理删除漏洞标签
 * @param {string} tag - 要删除的漏洞标签
 */
function handleVulnerabilityClose(tag) {
  busForm.vulnerabilities = busForm.vulnerabilities.filter(item => item !== tag);
}

/**
 * 提交总线表单
 */
function handleSubmit() {
  if (!busFormRef.value) return;
  
  busFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟添加成功
      ElMessage({
        message: '总线场景添加成功',
        type: 'success'
      });
      
      // 关闭对话框
      dialogVisible.value = false;
      
      // 实际应用中应该调用API保存数据
      console.log('提交的总线数据:', busForm);
      
      // 清空表单
      Object.keys(busForm).forEach(key => {
        if (Array.isArray(busForm[key])) {
          busForm[key] = [];
        } else {
          busForm[key] = '';
        }
      });
    } else {
      ElMessage({
        message: '表单填写有误，请检查',
        type: 'error'
      });
    }
  });
}
</script>

<style lang="scss" scoped>
.communication-bus {
  padding: 20px;
  

    
    .title {
      font-size: 22px;
      font-weight: bold;
      color: #333;
      margin: 0;
    }
  
  

  
  .bus-list {
    margin-top: 20px;
    
    .bus-card {
      height: 100%;
      margin-bottom: 20px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
      
      .bus-image {
        position: relative;
        height: 160px;
        overflow: hidden;
        
        .el-image {
          width: 100%;
          height: 100%;
        }
        
        .bus-badge {
          position: absolute;
          top: 10px;
          right: 10px;
          background-color: rgba(0, 0, 0, 0.7);
          color: #fff;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
      
      .bus-info {
        padding: 15px;
        
        .bus-name {
          font-size: 16px;
          font-weight: bold;
          margin: 0 0 10px 0;
          color: #333;
        }
        
        .bus-desc {
          font-size: 14px;
          color: #666;
          margin-bottom: 10px;
          height: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
        
        .bus-meta {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 15px;
          
          span {
            font-size: 13px;
            color: #909399;
            margin-right: 15px;
          }
        }
        
        .bus-footer {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  
  .bus-detail {
    .detail-section {
      margin-top: 20px;
      
      h4 {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
        position: relative;
        padding-left: 10px;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }
      
      p {
        color: #666;
        line-height: 1.6;
        margin: 0;
      }
      
      .architecture-image {
        margin: 15px 0;
        
        .el-image {
          max-width: 100%;
          max-height: 400px;
        }
      }
      
      .vulnerability-tag {
        margin-right: 10px;
        margin-bottom: 5px;
      }
    }
  }
  
  .vulnerability-input-tag {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  
  .vulnerability-input {
    width: 200px;
    margin-right: 10px;
    margin-bottom: 10px;
    vertical-align: bottom;
  }
  
  .button-new-tag {
    margin-bottom: 10px;
  }
  
  .upload-container {
    :deep(.el-upload--picture-card) {
      width: 120px;
      height: 120px;
      line-height: 120px;
    }
  }
}
</style> 